package cn.jbit.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2020/8/6
 */
public class NettyServer {

    public void bind(int port) throws InterruptedException {
        //线程组，负责accept事件
        EventLoopGroup  bossGroup=new NioEventLoopGroup();
        //线程组，负责read,write事件
        EventLoopGroup  workGroup=new NioEventLoopGroup();
        try {
            //服务端引导程序
            ServerBootstrap b = new ServerBootstrap();
            //指定通讯模式为NIO
            b.group(bossGroup, workGroup).channel(NioServerSocketChannel.class).
                 childOption(ChannelOption.TCP_NODELAY, true).
                    childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            socketChannel.pipeline().addLast(new NettyServerOutBoundHandler());
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });//可以指定参数，实现不同的Reactor模型
            //绑定完端口，让当前线程进入一个阻塞状态
            ChannelFuture f = b.bind(port).sync();
            System.out.println("server start");
            f.channel().closeFuture().sync();
        }catch (Exception e){

        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
            int port=8080;
            new NettyServer().bind(port);
    }
}
